import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
  Grid,
  Chip,
  Autocomplete,
  CircularProgress
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import apiRequest from '../utils/api';

const maintenanceTypes = [
  { value: 'REGULAR_MAINTENANCE', label: '定期保养' },
  { value: 'REPAIR', label: '故障维修' },
  { value: 'EMERGENCY_REPAIR', label: '紧急维修' },
  { value: 'ABNORMAL_HANDLING', label: '异常处理' }
];

const priorities = [
  { value: 'LOW', label: '低' },
  { value: 'MEDIUM', label: '中' },
  { value: 'HIGH', label: '高' },
  { value: 'URGENT', label: '紧急' }
];

const ReportMaintenance = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [vehicles, setVehicles] = useState([]);
  const [formData, setFormData] = useState({
    vehicleId: '',
    maintenanceType: 'ABNORMAL_HANDLING',
    description: '',
    priority: 'MEDIUM',
    location: '',
    estimatedCost: '',
    notes: '',
    tags: []
  });
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  useEffect(() => {
    loadUserVehicles();
  }, []);

  const loadUserVehicles = async () => {
    try {
      const response = await apiRequest.get('/api/vehicles/my');
      setVehicles(response.data);
    } catch (err) {
      console.error('加载车辆失败:', err);
      setError('加载车辆失败');
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setSuccess('');

    try {
      // 准备提交数据，确保与后端模型匹配
      const submitData = {
        vehicleId: formData.vehicleId,
        maintenanceType: formData.maintenanceType,
        description: formData.description.trim(),
        priority: formData.priority,
        location: formData.location,
        // 添加必需的地理位置字段，设置默认值
        latitude: 0,
        longitude: 0,
        // 移除货币符号，保持字符串类型（后端模型中是String）
        estimatedCost: formData.estimatedCost ? formData.estimatedCost.toString().replace(/[^0-9.]/g, '') : null,
        notes: formData.notes,
        // 保持tags为数组类型（后端期望List<String>格式）
        tags: formData.tags || []
      };
      
      // 打印提交数据用于调试
      console.log('提交的数据:', submitData);
      console.log('数据类型检查:', {
        vehicleId: typeof submitData.vehicleId,
        maintenanceType: typeof submitData.maintenanceType,
        description: typeof submitData.description,
        priority: typeof submitData.priority,
        estimatedCost: typeof submitData.estimatedCost,
        tags: typeof submitData.tags
      });
      
      const response = await apiRequest.post('/api/maintenance', submitData);
      setSuccess('异常报告提交成功！');
      setTimeout(() => {
        navigate('/maintenance-records');
      }, 2000);
    } catch (err) {
      setError(err.response?.data?.message || '提交失败，请重试');
      console.error('提交失败详细信息:', err);
      // 打印完整的错误响应信息
      if (err.response) {
        console.error('错误状态码:', err.response.status);
        console.error('错误响应数据:', err.response.data);
        console.error('错误响应头:', err.response.headers);
      } else if (err.request) {
        console.error('没有收到响应:', err.request);
      } else {
        console.error('请求配置错误:', err.message);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleTagsChange = (event, newValue) => {
    setFormData(prev => ({
      ...prev,
      tags: newValue
    }));
  };

  return (
    <Box sx={{ maxWidth: 800, mx: 'auto', p: 3 }}>
      <Typography variant="h4" gutterBottom>
        报告车辆异常或维修需求
      </Typography>

      {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
      {success && <Alert severity="success" sx={{ mb: 2 }}>{success}</Alert>}

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <FormControl fullWidth required>
                  <InputLabel>选择车辆</InputLabel>
                  <Select
                    name="vehicleId"
                    value={formData.vehicleId}
                    onChange={handleChange}
                    label="选择车辆"
                  >
                    {vehicles.map(vehicle => (
                      <MenuItem key={vehicle.id} value={vehicle.id}>
                        {vehicle.licensePlate} - {vehicle.brand} {vehicle.model}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12} md={6}>
                <FormControl fullWidth required>
                  <InputLabel>维修类型</InputLabel>
                  <Select
                    name="maintenanceType"
                    value={formData.maintenanceType}
                    onChange={handleChange}
                    label="维修类型"
                  >
                    {maintenanceTypes.map(type => (
                      <MenuItem key={type.value} value={type.value}>
                        {type.label}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12} md={6}>
                <FormControl fullWidth required>
                  <InputLabel>优先级</InputLabel>
                  <Select
                    name="priority"
                    value={formData.priority}
                    onChange={handleChange}
                    label="优先级"
                  >
                    {priorities.map(priority => (
                      <MenuItem key={priority.value} value={priority.value}>
                        {priority.label}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  name="location"
                  label="发生位置"
                  value={formData.location}
                  onChange={handleChange}
                  placeholder="例如：北京市朝阳区xxx路"
                />
              </Grid>

              <Grid item xs={12}>
                <TextField
                  fullWidth
                  required
                  name="description"
                  label="异常描述或维修需求"
                  multiline
                  rows={4}
                  value={formData.description}
                  onChange={handleChange}
                  placeholder="请详细描述车辆异常情况或维修需求..."
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  name="estimatedCost"
                  label="预估费用"
                  type="number"
                  value={formData.estimatedCost}
                  onChange={handleChange}
                  InputProps={{ startAdornment: '¥' }}
                />
              </Grid>

              <Grid item xs={12}>
                <Autocomplete
                  multiple
                  freeSolo
                  options={[]}
                  value={formData.tags}
                  onChange={handleTagsChange}
                  renderTags={(value, getTagProps) =>
                    value.map((option, index) => (
                      <Chip variant="outlined" label={option} {...getTagProps({ index })} />
                    ))
                  }
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      variant="outlined"
                      label="标签"
                      placeholder="输入标签后按回车"
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12}>
                <TextField
                  fullWidth
                  name="notes"
                  label="备注信息"
                  multiline
                  rows={3}
                  value={formData.notes}
                  onChange={handleChange}
                  placeholder="其他需要说明的信息..."
                />
              </Grid>

              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
                  <Button
                    variant="outlined"
                    onClick={() => navigate('/maintenance-records')}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    disabled={loading || !formData.vehicleId}
                  >
                    {loading ? <CircularProgress size={24} /> : '提交报告'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default ReportMaintenance;